package baiqitun.stupro.security.core.handler;

import baiqitun.stupro.common.exception.StuproException;
import baiqitun.stupro.common.exception.enums.support.StuproExceptionEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OAuthLogoutHandler implements LogoutHandler {
    @Autowired
    private TokenStore tokenStore;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String bearerToken = request.getHeader("Authorization");
        String refreshToken = request.getParameter("refreshToken");
        if (StringUtils.isBlank(bearerToken) || StringUtils.isBlank(refreshToken)){
            throw new StuproException(StuproExceptionEnum.PARAMETER_CANNOT_NULL).put("Authorization", bearerToken).put("refreshToken", refreshToken);
        }
        if (! bearerToken.startsWith("Bearer")){
            throw new StuproException(StuproExceptionEnum.PARAMETER_CANNOT_NULL).put("Authorization", null);
        }
        String accessToken = bearerToken.replace("Bearer ", "");
        OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(accessToken);
        if (oAuth2AccessToken == null){
            throw new InvalidTokenException("不存在的AccessToken");
        }
        OAuth2RefreshToken oauth2RefreshToken = tokenStore.readRefreshToken(refreshToken);
        if (oauth2RefreshToken == null){
            throw new InvalidTokenException("不存在的RefreshToken");
        }
        tokenStore.removeAccessToken(oAuth2AccessToken);
        tokenStore.removeRefreshToken(oauth2RefreshToken);
    }
}
